<?php
// +----------------------------------------------------------------------
// | 07FLYCRM [基于ThinkPHP5.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.07fly.xyz
// +----------------------------------------------------------------------
// | Professional because of focus  Persevering because of happiness
// +----------------------------------------------------------------------
// | Author: 开发人生 <goodkfrs@qq.com>
// +----------------------------------------------------------------------

namespace app\ten\logic;

/**
 * 菜单逻辑
 */
class TenMenu extends TenBase
{

    // 面包屑
    public static $crumbs = [];

    // 菜单Select结构
    public static $menuSelect = [];

    /**
     * 左侧菜单转视图
     */
    public function menuToView($menu_list = [], $child = 'child', $level = 0)
    {

        $menu_view = '';

        //遍历菜单列表
        foreach ($menu_list as $menu_info) {

            if (!empty($menu_info[$child]) && $menu_info['visible'] == 1) {

                $icon = empty($menu_info['icon']) ? 'fa-dot-circle-o' : $menu_info['icon'];
                $level_classname = '';
                if ($level == 0) {
                    $level_classname = "nav-second-level";
                } else if ($level == 1) {
                    $level_classname = "nav-third-level";
                }
                $menu_view .= '
                                        <li> <a href="#"> <i class="fa ' . $icon . '"></i> <span class="nav-label">' . $menu_info['name'] . '</span> <span class="fa arrow"></span> </a>
                                            <ul class="nav ' . $level_classname . '">
                                               ' . $this->menuToView($menu_info[$child], $child, $level + 1) . '
                                            </ul>
                                        </li>';
            } else {

                $icon = empty($menu_info['icon']) ? 'fa-circle-o' : $menu_info['icon'];

                //defined('BIND_MODULE') && $menu_info['url'] =$menu_info['module'].'/'.$menu_info['url'];//解决模块间的地址

                $menu_info['url'] = $menu_info['module'] . '/' . $menu_info['url'];//解决模块间的地址

                $url = url($menu_info['url']);

                if ($menu_info['visible'] == 1) {
                    //$menu_view .= "<li menu_id='".$menu_info['id']."'><a href='$url'><i class='fa $icon'></i> <span>".$menu_info['name']."</span></a></li>";
                    $menu_view .= '<li> <a class="J_menuItem" href="' . $url . '"> <i class="fa ' . $icon . '"></i> <span class="nav-label">' . $menu_info['name'] . '</span> </a> </li>';
                }
            }
        }

        return $menu_view;
    }

    /**
     * 菜单转Checkbox,用于菜单授权勾选
     *
     * @param array $menu_list 菜单列表
     * @param string $child 子菜单字段名
     * @param array $rules_array 菜单选中值
     * @return string
     */
    public function menuTreeCheckboxView($menu_list = [], $child = 'children', $rules_array = [])
    {
        $menu_view = '';
        $rules_array = is_array($rules_array) ? $rules_array : explode(',', $rules_array);
        //遍历菜单列表
        foreach ($menu_list as $menu_info) {
            //$icon = empty($menu_info['icon']) ? 'fa-dot-circle-o' : $menu_info['icon'];
            $icon = '';
            $checkbox_select = in_array($menu_info['id'], $rules_array) ? "checked='checked'" : '';
            if (!empty($menu_info[$child])) {
                $menu_view .= '<li class="has_child">';
                $menu_view .= "<span><i class='icon-plus-sign'></i></span><input class='rules_all' type='checkbox' name='menu_ids[]' value='" . $menu_info['id'] . "' $checkbox_select ><i class='fa $icon'></i> " . $menu_info['name'] . "";
                $menu_view .= "<ul style='display: none;'>";
                $menu_view .= $this->menuTreeCheckboxView($menu_info[$child], $child, $rules_array);
                $menu_view .= "</ul>";
                $menu_view .= "</li>";
            } else {
                $menu_view .= "<li>";
                $menu_view .= "<span><i></i></span><input type='checkbox' name='menu_ids[]' value='" . $menu_info['id'] . "'  $checkbox_select ><i class='fa $icon'></i> " . $menu_info['name'] . "";
                $menu_view .= "</li>";
                //$menu_view .= "<a class='auth-head'><input type='checkbox' name='rules[]' value='" . $menu_info['id'] . "'  $checkbox_select ><i class='fa $icon'></i> " . $menu_info['name'] . "&nbsp;&nbsp;</a>";
            }
        }
        return $menu_view;
    }

    /**
     * 获取自己及父菜单列表
     */
    public function getParentMenuList($menu_id = 0)
    {

        $menu_info = $this->getTenMenuInfo(['id' => $menu_id]);

        !empty($menu_info['pid']) && $this->getParentMenuList($menu_info['pid']);

        self::$crumbs [] = $menu_info;
    }

    /**
     * 获取面包屑
     */
    public function getCrumbsView()
    {
        $map['url'] = URL;
        $map['module'] = MODULE_NAME;

        $menu_info = $this->getTenMenuInfo($map);

        // 获取自己及父菜单列表
        !empty($menu_info['id']) && $this->getParentMenuList($menu_info['id']);

        $crumbs_view = '<div class="row white-bg" style="padding: 10px 5px 10px 20px;font-size: 13px;"><div class="col-sm-12">';

        $crumbs_view .= "<ol class='breadcrumb'>";

        foreach (self::$crumbs as $menu_info) {

            $icon = empty($menu_info['icon']) ? 'fa-circle-o' : $menu_info['icon'];

            $crumbs_view .= "<li><a><i class='fa $icon'></i> " . $menu_info['name'] . "</a></li>";
        }

        $crumbs_view .= "</ol>";
        $crumbs_view .= "</div></div>";

        return $crumbs_view;
    }

    /**
     * 获取菜单列表
     */
    public function getTenMenuList($where = [], $field = true, $order = '', $paginate = false)
    {
        $list = $this->modelTenMenu->getList($where, $field, $order, $paginate);
        foreach ($list as &$row) {
            $row['name'] = lang($row['name']);
        }
        return $list;
    }

    //得到tree的数据
    public function getTenMenuListTree($where = [], $field = "id,name,pid", $order = 'sort asc', $paginate = false)
    {
        $list = $this->getTenMenuList($where, $field, $order, $paginate)->toArray();
        $tree = list2tree($list);
        return $tree;
    }

    //得到tree的数据
    public function getTenMenuTreeSelect($where = [], $field = "id,name,pid", $order = 'sort asc', $paginate = false)
    {

        $list = $this->getTenMenuList($where, $field, $order, $paginate)->toArray();
        $data = list2select($list);
        return $data;
    }

    /**
     * 获取默认页面标题
     */
    public function getDefaultTitle()
    {
        $name = $this->modelTenMenu->getValue(['module' => MODULE_NAME, 'url' => URL], 'name');
        if (!empty($name)) {
            $name = lang($name);
        }
        return $name;
    }

    /**
     * 获取菜单信息
     */
    public function getTenMenuInfo($where = [], $field = true)
    {
        $info = $this->modelTenMenu->getInfo($where, $field);
        if (!empty($info)) {
            $info['name'] = lang($info['name']);
        }
        return $info;
    }

    /**
     * 菜单添加
     */
    public function tenMenuAdd($data = [])
    {
        $validate_result = $this->validateTenMenu->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenMenu->getError()];
        }
        $result = $this->modelTenMenu->setInfo($data);
        $result && action_log('新增', '新增菜单，name：' . $data['name']);
        $url = url('show', ['pid' => $data['pid'] ? $data['pid'] : 0]);
        return $result ? [RESULT_SUCCESS, '菜单添加成功', $url] : [RESULT_ERROR, $this->modelTenMenu->getError()];
    }

    /**
     * 菜单编辑
     */
    public function tenMenuEdit($data = [])
    {
        $validate_result = $this->validateTenMenu->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenMenu->getError()];
        }
        $url = url('show');
        $result = $this->modelTenMenu->setInfo($data);
        $result && action_log('编辑', '编辑菜单，name：' . $data['name']);
        return $result ? [RESULT_SUCCESS, '菜单编辑成功', $url] : [RESULT_ERROR, $this->modelTenMenu->getError()];
    }

    /**
     * 菜单删除
     */
    public function tenMenuDel($data = [])
    {
        $result = true;
        $url = url('show');
        if (!empty($data['id'])) {
            $ids = str2arr($data['id']);
            foreach ($ids as $id) {
                $son = $this->modelTenMenu->getValue(['pid' => $id], 'id');
                //无下级删除
                if (empty($son)) {
                    $result = $this->modelTenMenu->deleteInfo(['id' => $id], true);
                } else {
                    return [RESULT_ERROR, '勾选择菜单存在子菜单，请删除子菜单', $url];
                }
            }
        }
        $result && action_log('删除', '删除菜单，where：' . http_build_query($data));
        return $result ? [RESULT_SUCCESS, '菜单删除成功', $url] : [RESULT_ERROR, $this->modelTenMenu->getError()];
    }


    /**
     * 菜单移动
     */
    public function tenMenuMove($data = [])
    {
        if (empty($data['id']) || empty($data['pid'])) {
            return [RESULT_ERROR, '参数不全'];
            exit;
        } else {
            $ids = str2arr($data['id']);
            if (in_array($data['pid'], $ids)) {
                return [RESULT_ERROR, '不能移动到勾选栏目下面'];
            }
        }
        $where['id'] = ['in', $ids];
        $updata['pid'] = $data['pid'];
        $result = $this->modelTenMenu->updateInfo($where, $updata);
        $result && action_log('编辑', '移动菜单，name：' . $data['id']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '菜单编辑成功', $url] : [RESULT_ERROR, $this->modelTenMenu->getError()];
    }

    /**
     * 菜单复制
     * @param array $data
     * @return array
     * Author: 开发人生 goodkfrs@qq.com
     * Date: 2022/3/12 0012 10:53
     */
    public function tenMenuCopy($data = [])
    {
        if (empty($data['id']) || empty($data['pid'])) {
            return [RESULT_ERROR, '参数不全'];
            exit;
        } else {
            $ids = str2arr($data['id']);
            if (in_array($data['pid'], $ids)) {
                return [RESULT_ERROR, '不能复制到自己勾选栏目下面'];
            }
        }
        $where['id'] = ['in', $ids];
        $copylist = $this->modelTenMenu->getList($where, '', 'sort asc', false)->toArray();
        foreach ($copylist as $key => &$row) {
            $row['pid'] = $data['pid'];
            unset($row['id']);
            unset($row['create_time']);
            unset($row['update_time']);
        }
        $result = $this->modelTenMenu->setList($copylist);
        $result && action_log('编辑', '复制菜单，name：' . $data['id']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelTenMenu->getError()];
    }

    /**
     * 菜单复制
     * @param array $data
     * @return array
     * Author: 开发人生 goodkfrs@qq.com
     * Date: 2022/3/12 0012 10:53
     */
    public function tenMenuCopyOne($data = [])
    {

        if (empty($data['id'])) {
            return [RESULT_ERROR, '选择要复制参数不全'];
            exit;
        } else {
            $ids = str2arr($data['id']);
        }
        $where['id'] = ['in', $ids];
        $copylist = $this->modelTenMenu->getList($where, '', 'sort asc', false)->toArray();
        foreach ($copylist as $key => &$row) {
            unset($row['id']);
            unset($row['create_time']);
            unset($row['update_time']);
        }
        $result = $this->modelTenMenu->setList($copylist);
        $result && action_log('编辑', '复制菜单，name：' . $data['id']);
        $url = url('show');
        return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelTenMenu->getError()];
    }

    //导入菜单
    public function tenMenuImportFile($data = '')
    {
        $filename = $this->logicUpload->getUploadFilePathname($data);
        if (file_exists($filename)) {
            $content = file_get_contents($filename);
            $content = isJson($content, true);
            $this->modelTenMenu->tenMenuImport($content);
        }
        return [RESULT_SUCCESS, '操作成功'];
    }


    /**
     * 批量导出菜单
     * @param array $data 菜单数据
     * @param string $mod 模型名称或插件名称
     * @param string $type [module,plugins]
     * @param int $pid 父ID
     * @return bool
     * @author 开发人生 <574249366@qq.com>
     */
    public function tenMenuExport($modulename = '')
    {
        $where = [];
        if (!empty($modulename)) {
            $where['module'] = ['=', $modulename];
        }
        $list = $this->modelTenMenu->getList($where, '', '', false)->toArray();
        $menuTree = list2tree2menu($list);
        $content = json_encode($menuTree, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        $module_dir = PATH_APP . $modulename . DS . 'data' . DS;
        file_put_contents($module_dir . 'menu.json', $content);//新的json文件
        return [RESULT_SUCCESS, '操作成功'];
    }

    /**
     * 获取菜单列表
     */
    public function getTenMenuAllPidPath($menuId = 0)
    {
        $allPid = $this->modelTenMenu->getTenMenuAllPid($menuId);
        $allPid = array_reverse($allPid);
        $crumbs_view = '<div class="row white-bg" style="padding: 10px 5px 10px 20px;font-size: 13px;"><div class="col-sm-12">';
        $crumbs_view .= "<ol class='breadcrumb'>";
        foreach ($allPid as $k => $id) {
            $menu_info = $this->modelTenMenu->getInfo(['id' => $id], 'name');
            $icon = empty($menu_info['icon']) ? 'fa-circle-o' : $menu_info['icon'];
            $crumbs_view .= "<li><a><i class='fa $icon'></i> " . $menu_info['name'] . "</a></li>";
        }
        $crumbs_view .= "</ol>";
        $crumbs_view .= "</div></div>";
        return $crumbs_view;
    }

    //查询条件
    public function getWhere($data = [])
    {
        $where = [];
        //关键字查
        !empty($data['keywords']) && $where['name|module'] = ['like', '%' . $data['keywords'] . '%'];
        if (isset($data['pid'])) {
            if (!empty($data['pid'])) {
                $where['pid'] = ['in', $data['pid']];
            } else {
                $where['pid'] = ['in', '0'];
            }
        }
        //只显示启模块菜单
        $modules = $this->modelTenModule->getColumn(['visible' => 1], 'module');
        $modules[] = 'plat';//平台模块，默认显示
        $where['module'] = ['in', $modules];

        //模块指定
        if(!empty($data['module'])){
            $where['module'] = ['in', $data['module']];
        }
        return $where;
    }
}